
import time
import redis
from . import tool_cache


class LJRedis():
    def __init__(self, host="127.0.0.1", port=6379, db=0, password=None) -> None:
        self.host = host
        self.port = port
        self.db = db
        self.password = password
        self.client = redis.Redis(
            host=host, port=port, db=db, password=password)

    def select(self, db=None):
        self.client.select(db or self.db)

    def val_gen(self, key, fun, **option):
        # 切换库
        self.select(option.get("db"))
        # 获取值
        val = self.client.get(key)
        if not val:
            val = fun()
        # 切回默认库
        self.select()

    def expire_time(self, key, expire_time):
        if not expire_time or not key:
            return
        self.client.expireat(key, int(time.time()) + expire_time)

    def val(self, key, val=None, **option):
        # 切换库
        self.select(option.get("db"))
        # 赋值
        if val:
            self.client.set(key, val)
        # 获取值
        val = self.client.get(key)
        # 动态值
        if not val and option.get("fun"):
            val = option.get("fun")()
            self.client.set(key, val)
        # 设置过期时间
        self.expire_time(key, option.get("expire_time"))
        # 切回默认库
        self.select()
        return val

    def lock_run(self, key, fun, expire_time=60):
        # 锁定运行 - 如果时间没到，则不运行（保障一段时间内只运行一次）
        if not key or not fun:
            return
        if self.client.set(f"lj:lock:{key}", "locked", ex=expire_time, nx=True):
            fun()


@tool_cache.lj_wrapper_cache(key="tool_redis_init_default", expiration_seconds=60 * 60 * 2)
def init_default():
    return LJRedis("61.52.247.249", 20001, 6, "zzfmhb")
